import { ParseAuth } from "@/utils/auth.js";
import redisClient from "~/utils/redis";

const isMoblie = (event) => {
    const userAgent = getHeader(event, "User-Agent");
    return /iPhone|iPad|iPod|Android/i.test(userAgent);
};

const getPlatform = (event) => {
    return isMoblie(event) ? "m" : "p";
};

const getToken = (event) => {
    const cookies = parseCookies(event);
    return cookies["ykj_token"];
};

export default defineEventHandler(async (event) => {
    const token = getToken(event);
    const query = await getQuery(event);
    const code = query["code"];
    const GoToLoginPage = async () => {
        await sendRedirect(event, "/login.html?opencode=" + code, 302);
    };

    if (token) {
        const userInfo = ParseAuth(token);
        if (userInfo && userInfo.id) {
            const saveToken = await redisClient.getVal(
                `token-${getPlatform(event)}-${userInfo.id}`
            );

            if (process.env.NODE_ENV === "development" || saveToken == token) {
                return `
                    <!DOCTYPE html>
                    <html>
                    
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1.0">
                        <title>北京华锐云空间</title>
                        <link rel="stylesheet" href="./Comment/index.css">
                        <script src="https://www.ykjhr.com/js/sso.js"></script>
                    </head>
                    <body>
                        <div>登录成功，<span class="num">3</span>秒后自动关闭页面！</div>
                        <script>
                            var num = document.querySelector('.num');
                            opener.postMessage({ token: "${token}", code: "${code}" }, "*");
                            function loop() {
                                setTimeout(() => {
                                    if(num.innerText == 0) window.close();
                                    else {
                                        num.innerText = num.innerText - 1;
                                        loop();
                                    }
                                }, 1000)
                            }
                            loop();
                        </script>
                    </body>
                    
                    </html>
                `;
            }
        }
    }
    await GoToLoginPage();
    return "ok";
});